package com.luych.toolbox.common.service.page;

import com.luych.toolbox.common.page.PageParam;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.List;

public class SpringPageParamAdapter implements Pageable {

    private final PageParam commonPage;

    public SpringPageParamAdapter(PageParam pageParam) {
        this.commonPage = pageParam;
    }


    @Override
    public int getPageNumber() {
        return (int) commonPage.getPageNumber();
    }

    @Override
    public int getPageSize() {
        return (int) commonPage.getPageSize();
    }

    @Override
    public long getOffset() {
        return commonPage.getPageStart();
    }

    @Override
    public Sort getSort() {
        if (commonPage.getSorts().isEmpty()) {
            return Sort.unsorted();
        }
        Sort springSort = Sort.unsorted();
        for (com.luych.toolbox.common.page.Sort commonSort : commonPage.getSorts()) {
            Sort newSort = Sort.by(Sort.Direction.fromString(commonSort.getOrder()), commonSort.getSort());
            springSort = springSort.and(newSort);
        }
        return springSort;
    }

    @Override
    public Pageable next() {
        return new SpringPageParamAdapter(new PageParam() {
            @Override
            public long getPageNumber() {
                return commonPage.getPageNumber() + 1;
            }

            @Override
            public long getPageSize() {
                return commonPage.getPageSize();
            }

            @Override
            public List<com.luych.toolbox.common.page.Sort> getSorts() {
                return commonPage.getSorts();
            }
        });
    }

    @Override
    public Pageable previousOrFirst() {
        return new SpringPageParamAdapter(new PageParam() {
            @Override
            public long getPageNumber() {
                return commonPage.getPageNumber() - 1;
            }

            @Override
            public long getPageSize() {
                return commonPage.getPageSize();
            }

            @Override
            public List<com.luych.toolbox.common.page.Sort> getSorts() {
                return commonPage.getSorts();
            }
        });
    }

    @Override
    public Pageable first() {
        return new SpringPageParamAdapter(new PageParam() {
            @Override
            public long getPageNumber() {
                return 1;
            }

            @Override
            public long getPageSize() {
                return commonPage.getPageSize();
            }

            @Override
            public List<com.luych.toolbox.common.page.Sort> getSorts() {
                return commonPage.getSorts();
            }
        });
    }

    @Override
    public boolean hasPrevious() {
        return commonPage.getPageNumber() > 1;
    }
}
